﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data.Linq;
using System.Transactions;

namespace TradeForm
{
    public partial class FrmTradeForm : Form
    {
        private string _defcode = string.Empty;
        public string DefCode
        {
            get { return this._defcode; }
            //  set { this._defcode = value; }
        }
        public bool IsNew = true;

        public FrmTradeForm()
        {
            InitializeComponent();
            this.IsNew = true;
        }

        public FrmTradeForm(string defcode)
        {
            InitializeComponent();
            this._defcode = defcode;
            this.IsNew = false;
        }

        public FrmTradeForm(string defcode, bool Iscopy)
        {
            InitializeComponent();
            this._defcode = defcode;
            this.IsNew = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (CheckFormData())
            {
                this.ValidateChildren();

                saveBill();
            }
        }

        private bool CheckFormData()
        {
            #region 校验
            if (string.IsNullOrEmpty(this.txtDefCode.Text.Trim()))
            {
                MessageBox.Show("业务编号必填。", "注意", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtDefCode.Focus();
                return false;
            }
            if (!string.IsNullOrEmpty(this.txtTotalCount.Text.Trim()))
            {
                try
                {
                    decimal totalCount = Convert.ToDecimal(this.txtTotalCount.Text.Trim());
                }
                catch
                {
                    MessageBox.Show("总件数只能是数字。", "注意", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
            }

            if (!string.IsNullOrEmpty(this.txtTotalQty.Text.Trim()))
            {
                try
                {
                    decimal totalCount = Convert.ToDecimal(this.txtTotalQty.Text.Trim());
                }
                catch
                {
                    MessageBox.Show("总数量只能是数字。", "注意", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }

            }

            if (!string.IsNullOrEmpty(this.txtTotalGrossWeight.Text.Trim()))
            {
                try
                {
                    decimal totalCount = Convert.ToDecimal(this.txtTotalGrossWeight.Text.Trim());
                }
                catch
                {
                    MessageBox.Show("总毛重只能是数字。", "注意", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }

            }

            if (!string.IsNullOrEmpty(this.txtTotalMeas.Text.Trim()))
            {
                try
                {
                    decimal totalCount = Convert.ToDecimal(this.txtTotalMeas.Text.Trim());
                }
                catch
                {
                    MessageBox.Show("总体积只能是数字。", "注意", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }

            }

            if (!string.IsNullOrEmpty(this.txtTotalNetWeight.Text.Trim()))
            {
                try
                {
                    decimal totalCount = Convert.ToDecimal(this.txtTotalNetWeight.Text.Trim());
                }
                catch
                {
                    MessageBox.Show("总净重只能是数字。", "注意", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }

            }
            #endregion
            return true;
        }

        private void saveBill()
        {
            DataDBDataContext dbcntxt = new DataDBDataContext
                (ConfigurationManager.ConnectionStrings["TradeForm.Properties.Settings.dbConnectionString"].ConnectionString);


            this._defcode = this.txtDefCode.Text.Trim();
            BillExchange billex = new BillExchange();
            ProFormaInvoice pinv = new ProFormaInvoice();
            ProFormaInvoiceGoods pinvGoods = new ProFormaInvoiceGoods();
            Invoice inv = new Invoice();
            Contract cont = new Contract();
            CustomsDeclaration cust = new CustomsDeclaration();
            ConsignBill consb = new ConsignBill();
            PackList pack = new PackList();
            GoodsSummery goodsSum = new GoodsSummery();

            bool IsExist = false;

            dbcntxt.Connection.Open();
            dbcntxt.Transaction = dbcntxt.Connection.BeginTransaction(System.Data.IsolationLevel.Serializable);


            try
            {
                #region//BillExchange
                var billexs = from bill in dbcntxt.BillExchange
                              where bill.DefCode == this._defcode
                              select bill;
                if (billexs.Count() > 0)
                {
                    billex = billexs.First();
                    IsExist = true;
                }
                else
                {
                    IsExist = false;
                }
                billex.DefCode = this.txtDefCode.Text;
                billex.Address = this.txtBiExAddress.Text;
                billex.Amount = string.IsNullOrEmpty(this.txtBiExAmount.Text.Trim()) ? 0.0m : Convert.ToDecimal(this.txtBiExAmount.Text);
                billex.BiExNo = this.txtBiExNo.Text;
                billex.Currency = this.txtBiExCurrency.Text;
                //billex.GreatAmount = string.IsNullOrEmpty(this.txtBiExAmount.Text.Trim()) ? "" : Number2English.NumberToString(Convert.ToDouble(this.txtBiExAmount.Text));
                billex.GreatAmount = this.txtBiExGreateAmount.Text;
                billex.Interest = this.txtBiExInterest.Text;
                billex.LCBank = this.txtBiExLCBank.Text;
                billex.LCDate = this.dtpBiExLCDate.Value.Date;
                billex.LCno = this.txtBiExLCno.Text;
                billex.LimitDays = this.txtBiExDays.Text;
                //billex.Payee = this.txtBiExPayee.Text;
                billex.Payer = this.txtBiExPayer.Text;
                billex.AmountSay = this.txtBiExAmountSay.Text;
                if (!IsExist)
                {
                    dbcntxt.BillExchange.InsertOnSubmit(billex);
                }
                #endregion

                #region //ProFormaInvoice
                var pinvs = from bill in dbcntxt.ProFormaInvoice
                            where bill.DefCode == this.txtDefCode.Text.Trim()
                            select bill;
                if (pinvs.Count() > 0)
                {
                    pinv = pinvs.First();
                    IsExist = true;
                }
                else
                {
                    IsExist = false;
                }
                pinv.DefCode = this.txtDefCode.Text.Trim();
                pinv.Consignee = this.txtProFormaConsignee.Text;
                pinv.DestPort = this.cmbProFormaDestPort.Text;
                pinv.FromPort = this.cmbProFormaFromPort.Text;
                pinv.GatherInfo = this.txtProFormaPayeeInfo.Text;
                pinv.InvoiceDate = this.dtpProFormaDate.Value.Date;
                pinv.InvoiceNo = this.txtProFormaInvoiceNo.Text;
                pinv.Mark = this.txtProFormaRemark.Text;
                pinv.PriceTerms = this.cmbProFormaPriceTerms.Text;
                if (!IsExist)
                {
                    dbcntxt.ProFormaInvoice.InsertOnSubmit(pinv);
                }
                #endregion

                #region //ProFormaInvoiceGoods
                var pinvGoodss = from good in dbcntxt.ProFormaInvoiceGoods
                                 where good.DefCode == this._defcode
                                 select good;
                foreach (ProFormaInvoiceGoods item in pinvGoodss)
                {
                    dbcntxt.ProFormaInvoiceGoods.DeleteOnSubmit(item);
                }
                dbcntxt.SubmitChanges(ConflictMode.FailOnFirstConflict);
                foreach (DataGridViewRow row in this.dgvProforma.Rows)
                {
                    if (!row.IsNewRow)
                    {
                        ProFormaInvoiceGoods goods = new ProFormaInvoiceGoods();
                        goods.Amount = row.Cells["ColProformaAmount"].Value == null ? 0.0m : Convert.ToDecimal(row.Cells["ColProformaAmount"].Value);
                        goods.Currency = row.Cells["ColProformaCurrency"].Value == null ? "" : row.Cells["ColProformaCurrency"].Value.ToString();
                        goods.ArtNo = row.Cells["ColProformaArtNo"].Value == null ? "" : row.Cells["ColProformaArtNo"].Value.ToString();
                        goods.ItemNo = row.Index + 1;
                        goods.GoodsName = row.Cells["ColProformaGoodsName"].Value == null ? "" : row.Cells["ColProformaGoodsName"].Value.ToString();
                        goods.Qty = row.Cells["ColProformaQty"].Value == null ? 0.0m : Convert.ToDecimal(row.Cells["ColProformaQty"].Value);
                        goods.UnitPrice = row.Cells["ColProformaUnitPrice"].Value == null ? 0.0m : Convert.ToDecimal(row.Cells["ColProformaUnitPrice"].Value);
                        goods.DefCode = this._defcode;
                        goods.QtyUnit = row.Cells["ColProformaQtyUnit"].Value == null ? "" : row.Cells["ColProformaQtyUnit"].Value.ToString();
                        dbcntxt.ProFormaInvoiceGoods.InsertOnSubmit(goods);
                    }
                }
                #endregion

                #region//Invoice
                var invs = from bill in dbcntxt.Invoice
                           where bill.DefCode == this._defcode
                           select bill;
                if (invs.Count() > 0)
                {
                    inv = invs.First();
                    IsExist = true;
                }
                else
                {
                    IsExist = false;
                }
                inv.DefCode = this.txtDefCode.Text;
                inv.Consignee = this.txtInvConsignee.Text;
                inv.ContractNo = this.txtInvContractNo.Text;
                inv.DestPort = this.cmbInvDestPort.Text;
                inv.FromPort = this.cmbInvFromPort.Text;
                inv.InvoiceDate = this.dtpInvInvoiceDate.Value.Date;
                inv.InvoiceNo = this.txtInvInvoiceNo.Text;
                inv.Mark = this.txtInvMarks.Text;
                inv.PriceTerms = this.cmbInvPriceTerms.Text;
                inv.Remark = this.txtInvRemark.Text;
                if (!IsExist)
                {
                    dbcntxt.Invoice.InsertOnSubmit(inv);
                }
                #endregion

                #region //Contract
                var conts = from bill in dbcntxt.Contract
                            where bill.DefCode == this._defcode
                            select bill;
                if (conts.Count() > 0)
                {
                    cont = conts.First();
                    IsExist = true;
                }
                else
                {
                    IsExist = false;
                }
                cont.DefCode = this.txtDefCode.Text;
                cont.Consignee = this.txtContConsignee.Text;
                cont.ContractDate = this.dtpContContractDate.Value.Date;
                cont.ContractNo = this.txtContContractNo.Text;
                cont.DestPort = this.cmbContDestPort.Text;
                cont.FromPort = this.cmbContFromPort.Text;
                cont.PaymentMethod = this.cmbContPaymentMethod.Text;
                cont.PriceTerms = this.cmbContPriceTerms.Text;
                cont.Remark = this.txtContRemark.Text;
                cont.ShipmentDate = this.dtpContShipmentDate.Value.Date;
                if (!IsExist)
                {
                    dbcntxt.Contract.InsertOnSubmit(cont);
                }
                #endregion

                #region //CustomsDeclaration
                var custs = from bill in dbcntxt.CustomsDeclaration
                            where bill.DefCode == this._defcode
                            select bill;
                if (custs.Count() > 0)
                {
                    cust = custs.First();
                    IsExist = true;
                }
                else
                {
                    IsExist = false;
                }
                cust.DefCode = this.txtDefCode.Text;
                cust.ApprovalNo = this.txtCustApprovalNo.Text;
                cust.AttachFile = this.txtCustAttachFile.Text;
                cust.BillLadingNo = this.txtCustBillLadingNo.Text;
                cust.Consignor = this.txtCustConsignor.Text;
                cust.ContainnerNO = this.txtCustContainnerNO.Text;
                cust.ContractNo = this.txtCustContractNo.Text;
                cust.Conveyance = this.cmbCustConveyance.Text;
                cust.CustomDate = this.dtpCustCustomDate.Value.Date;
                cust.DestPort = this.cmbCustDestPort.Text;
                cust.ExpDate = this.dtpCustExportDate.Value.Date;
                cust.FillDate = this.dtpCustFilDate.Value.Date;
                cust.Freight = this.txtCustFreight.Text;
                cust.FromPort = this.cmbCustFromPort.Text;
                cust.GoodsFrom = this.txtCustGoodsFrom.Text;
                cust.Insurance = this.txtCustInsurance.Text;
                cust.Manufacture = this.txtCustManufacture.Text;
                cust.Mark = this.txtCustMark.Text;
                cust.MiscellaneousFees = this.txtCustOtherFees.Text;
                cust.OperateCompany = this.txtCustOperateCom.Text;
                cust.PackType = this.txtCustPackType.Text;
                cust.RecordNo = this.txtCustRecordNo.Text;
                cust.Remittanceway = this.cmbCustRemittanceWay.Text;
                cust.Tax = this.txtCustTax.Text;
                cust.TaxDutyFree = this.txtCustTaxDutyFree.Text;
                cust.TotalCount = string.IsNullOrEmpty(this.txtCustGoodsNum.Text) ? 0.0m : Convert.ToDecimal(this.txtCustGoodsNum.Text);
                cust.TotalGrossWeight = string.IsNullOrEmpty(this.txtCustGrossWeight.Text) ? 0.0m : Convert.ToDecimal(this.txtCustGrossWeight.Text);
                cust.TotalNetWeight = string.IsNullOrEmpty(this.txtCustNetWeight.Text) ? 0.0m : Convert.ToDecimal(this.txtCustNetWeight.Text);
                // cust.TradeCountry = this.txtCustTradeCountry.Text;
                cust.TradeKind = this.txtCustTradeTerms.Text;
                cust.TransportMode = this.txtCustTransportMode.Text;
                cust.TurnoverWay = this.txtCustTurnoverWay.Text;
                cust.WarrantNo = this.txtCustWarrantNo.Text;
                cust.TradeCountry = this.cmbCustTradeCountry.Text;

                if (!IsExist)
                {
                    dbcntxt.CustomsDeclaration.InsertOnSubmit(cust);
                }
                #endregion

                #region //ConsignBill
                var consbs = from bill in dbcntxt.ConsignBill
                             where bill.DefCode == this._defcode
                             select bill;
                if (consbs.Count() > 0)
                {
                    consb = consbs.First();
                    IsExist = true;
                }
                else
                {
                    IsExist = false;
                }
                consb.DefCode = this.txtDefCode.Text;
                consb.CanBatch = this.chkFreCanBatch.Checked;
                consb.CanTranshipment = this.chkFreCanTranshipment.Checked;
                consb.Consignee = this.txtFreConsignee.Text;
                consb.DestPort = this.cmbFreDestPort.Text;
                // consb.Freight = this.txtFreFreight.Text;
                consb.FinalDestPort = this.cmbFreFinalDestPort.Text;
                consb.Mark = this.txtFreMark.Text;
                consb.NotifyParty = this.txtFreNotifyParty.Text;
                consb.PaymentMethod = this.cmbFrePaymentTerms.Text;
                consb.ShipmentDate = this.dtpFreShipmentDate.Value.Date;
                consb.Shipper = this.txtFreShipper.Text;
                consb.ValiDate = this.dtpFreValiDate.Value.Date;
                consb.FromPort = this.cmbFreLoadPort.Text;
                consb.Remark = this.txtFreRemark.Text;

                if (!IsExist)
                {
                    dbcntxt.ConsignBill.InsertOnSubmit(consb);
                }
                #endregion

                #region //PackList
                var packs = from bill in dbcntxt.PackList
                            where bill.DefCode == this._defcode
                            select bill;
                if (packs.Count() > 0)
                {
                    pack = packs.First();
                    IsExist = true;
                }
                else
                {
                    IsExist = false;
                }
                pack.DefCode = this.txtDefCode.Text;
                pack.InvoiceNo = this.txtPackInvoiceNo.Text;
                pack.Mark = this.txtPackMark.Text;
                pack.TotalCount = string.IsNullOrEmpty(this.txtPackTotalCount.Text) ? 0.0m : Convert.ToDecimal(this.txtPackTotalCount.Text);
                pack.TotalCountUnit = this.txtPackTotalCountUnit.Text;
                pack.TotalGoodsName = this.txtPackGoodsName.Text;
                pack.Remark = this.txtPackRemark.Text;
                pack.ContractNo = this.txtPackContractNo.Text;
                pack.PackDate = this.dtpPackDate.Value;

                if (!IsExist)
                {
                    dbcntxt.PackList.InsertOnSubmit(pack);
                }
                #endregion

                #region //PackListGoods
                var packGoods = from good in dbcntxt.PackListGoods
                                where good.DefCode == this._defcode
                                select good;
                foreach (PackListGoods item in packGoods)
                {
                    dbcntxt.PackListGoods.DeleteOnSubmit(item);
                }
                dbcntxt.SubmitChanges(ConflictMode.FailOnFirstConflict);
                PackListGoods packgood = null;
                foreach (DataGridViewRow row in this.gdvPacklist.Rows)
                {
                    if (!row.IsNewRow)
                    {
                        packgood = new PackListGoods();
                        //packgood.ArtNo = row.Cells["ColPackArtNo"].Value == null ? "" : row.Cells["ColPackArtNo"].Value.ToString();
                        packgood.ItemNo = row.Index + 1;
                        packgood.CaseNo = row.Cells["ColPackCaseNo"].Value == null ? "" : row.Cells["ColPackCaseNo"].Value.ToString();
                        //packgood.ColorCN = row.Cells["ColPackColorCN"].Value == null ? "" : row.Cells["ColPackColorCN"].Value.ToString();
                        //packgood.ColorEN = row.Cells["ColPackColorEN"].Value == null ? "" : row.Cells["ColPackColorEN"].Value.ToString();
                        packgood.Ctns = row.Cells["ColPackCtns"].Value == null ? 0.0m : Convert.ToDecimal(row.Cells["ColPackCtns"].Value);
                        packgood.GrossWeight = row.Cells["ColPackGrossWeight"].Value == null ? 0.0m : Convert.ToDecimal(row.Cells["ColPackGrossWeight"].Value);
                        //packgood.Meas = row.Cells["ColPackMeas"].Value == null ? "0" : row.Cells["ColPackMeas"].Value.ToString();
                        packgood.NetWeight = row.Cells["ColPackNetWeight"].Value == null ? 0.0m : Convert.ToDecimal(row.Cells["ColPackNetWeight"].Value);
                        packgood.PONo = row.Cells["ColPackPONo"].Value == null ? "" : row.Cells["ColPackPONo"].Value.ToString();
                        packgood.Qty = row.Cells["ColPackQnty"].Value == null ? 0.0m : Convert.ToDecimal(row.Cells["ColPackQnty"].Value);
                        packgood.QtyUnit = row.Cells["ColPackQtyUnit"].Value == null ? "" : row.Cells["ColPackQtyUnit"].Value.ToString();
                        packgood.PkgDesc = row.Cells["ColPackPKGDesc"].Value == null ? "" : row.Cells["ColPackPKGDesc"].Value.ToString();
                        //packgood.Size10 = row.Cells["ColSize10"].Value == null ? "" : row.Cells["ColSize10"].Value.ToString();
                        //packgood.Size11 = row.Cells["ColSize11"].Value == null ? "" : row.Cells["ColSize11"].Value.ToString();
                        //packgood.Size12 = row.Cells["ColSize12"].Value == null ? "" : row.Cells["ColSize12"].Value.ToString();
                        //packgood.Size13 = row.Cells["ColSize13"].Value == null ? "" : row.Cells["ColSize13"].Value.ToString();
                        //packgood.Size14 = row.Cells["ColSize14"].Value == null ? "" : row.Cells["ColSize14"].Value.ToString();
                        //packgood.Size15 = row.Cells["ColSize15"].Value == null ? "" : row.Cells["ColSize15"].Value.ToString();
                        //packgood.Size5 = row.Cells["ColSize5"].Value == null ? "" : row.Cells["ColSize5"].Value.ToString();
                        //packgood.Size6 = row.Cells["ColSize6"].Value == null ? "" : row.Cells["ColSize6"].Value.ToString();
                        //packgood.Size7 = row.Cells["ColSize7"].Value == null ? "" : row.Cells["ColSize7"].Value.ToString();
                        //packgood.Size8 = row.Cells["ColSize8"].Value == null ? "" : row.Cells["ColSize8"].Value.ToString();
                        //packgood.Size9 = row.Cells["ColSize9"].Value == null ? "" : row.Cells["ColSize9"].Value.ToString();
                        //packgood.SizeM = row.Cells["ColSizeM"].Value == null ? "" : row.Cells["ColSizeM"].Value.ToString();
                        //packgood.StockNo = row.Cells["ColPackStockNo"].Value == null ? "" : row.Cells["ColPackStockNo"].Value.ToString();

                        packgood.DefCode = this._defcode;
                        dbcntxt.PackListGoods.InsertOnSubmit(packgood);
                    }
                }

                #endregion

                #region //GoodsSummery
                var goodsSums = from gs in dbcntxt.GoodsSummery
                                where gs.DefCode == this._defcode
                                select gs;
                if (goodsSums.Count() > 0)
                {
                    goodsSum = goodsSums.First();
                    IsExist = true;
                }
                else
                {
                    IsExist = false;
                }
                goodsSum.DefCode = this.txtDefCode.Text;
                goodsSum.GreatAmount = this.txtGreatAmount.Text;
                goodsSum.PackType = this.txtPackType.Text;
                goodsSum.TotalCount = string.IsNullOrEmpty(this.txtTotalCount.Text) ? 0.0m : Convert.ToDecimal(this.txtTotalCount.Text);
                goodsSum.TotalCName = this.txtTotalCName.Text;
                goodsSum.TotalCountUnit = this.txtTotalCountUnit.Text;
                goodsSum.TotalEName = this.txtTotalEName.Text;
                goodsSum.TotalGrossWeight = string.IsNullOrEmpty(this.txtTotalGrossWeight.Text) ? 0.0m : Convert.ToDecimal(this.txtTotalGrossWeight.Text);
                goodsSum.TotalMeas = string.IsNullOrEmpty(this.txtTotalMeas.Text) ? 0.0m : Convert.ToDecimal(this.txtTotalMeas.Text);
                goodsSum.TotalNetWeight = string.IsNullOrEmpty(this.txtTotalNetWeight.Text) ? 0.0m : Convert.ToDecimal(this.txtTotalNetWeight.Text);
                goodsSum.TotalQty = string.IsNullOrEmpty(this.txtTotalQty.Text) ? 0.0m : Convert.ToDecimal(this.txtTotalQty.Text);
                goodsSum.TotalQtyUnit = this.txtTotalQtyUnit.Text;

                goodsSum.TotalMeasUnit = this.txtTotalMeasUnit.Text;
                goodsSum.TotalNetWeightUnit = this.txtTotalNetWeightUnit.Text;
                goodsSum.TotalGrossWeightUnit = this.txtTotalGrossWeightUnit.Text;

                if (!IsExist)
                {
                    dbcntxt.GoodsSummery.InsertOnSubmit(goodsSum);
                }
                #endregion

                #region //GoodsDetail
                var goodDetails = from good in dbcntxt.GoodsDetail
                                  where good.DefCode == this._defcode
                                  select good;
                foreach (GoodsDetail item in goodDetails)
                {
                    dbcntxt.GoodsDetail.DeleteOnSubmit(item);
                }
                dbcntxt.SubmitChanges(ConflictMode.FailOnFirstConflict);
                GoodsDetail goodsDtl = null;
                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    if (!row.IsNewRow)
                    {
                        goodsDtl = new GoodsDetail();
                        goodsDtl.Amount = row.Cells["ColAmount"].Value == null ? 0.0m : Convert.ToDecimal(row.Cells["ColAmount"].Value);
                        goodsDtl.Currency = row.Cells["ColCurrency"].Value == null ? "" : row.Cells["ColCurrency"].Value.ToString();
                        goodsDtl.GoodsEName = row.Cells["ColGoodsEName"].Value == null ? "" : row.Cells["ColGoodsEName"].Value.ToString();
                        goodsDtl.ItemNo = row.Index + 1;
                        goodsDtl.HSCode = row.Cells["ColHScode"].Value == null ? "" : row.Cells["ColHScode"].Value.ToString();
                        goodsDtl.GoodsName = row.Cells["ColGoodsName"].Value == null ? "" : row.Cells["ColGoodsName"].Value.ToString();
                        goodsDtl.Qty = row.Cells["ColQty"].Value == null ? 0.0m : Convert.ToDecimal(row.Cells["ColQty"].Value);
                        goodsDtl.UnitPrice = row.Cells["ColUnitPrice"].Value == null ? 0.0m : Convert.ToDecimal(row.Cells["ColUnitPrice"].Value);
                        goodsDtl.Measures = row.Cells["ColMeasures"].Value == null ? 0.0m : Convert.ToDecimal(row.Cells["ColMeasures"].Value);
                        goodsDtl.GrossWeight = row.Cells["ColGrossWeight"].Value == null ? 0.0m : Convert.ToDecimal(row.Cells["ColGrossWeight"].Value);
                        goodsDtl.NetWeight = row.Cells["ColNetWeight"].Value == null ? 0.0m : Convert.ToDecimal(row.Cells["ColNetWeight"].Value);
                        goodsDtl.DefCode = this._defcode;
                        goodsDtl.QtyUnit = row.Cells["ColQtyUnit"].Value == null ? "" : row.Cells["ColQtyUnit"].Value.ToString();

                        goodsDtl.GMSNo = row.Cells["ColGMSNo"].Value == null ? "" : row.Cells["ColGMSNo"].Value.ToString();
                        goodsDtl.ArtNo = row.Cells["ColArtNo"].Value == null ? "" : row.Cells["ColArtNo"].Value.ToString();
                        goodsDtl.PONo = row.Cells["ColPONo"].Value == null ? "" : row.Cells["ColPONo"].Value.ToString();
                        dbcntxt.GoodsDetail.InsertOnSubmit(goodsDtl);
                    }
                }

                #endregion

                dbcntxt.SubmitChanges(ConflictMode.FailOnFirstConflict);
                dbcntxt.Transaction.Commit();
            }
            catch (Exception e)
            {
                dbcntxt.Transaction.Rollback();
                MessageBox.Show("保存失败。\r\n\r" + e.ToString());
                return;
            }

            MessageBox.Show("保存成功。");
            this.IsNew = false;
            this.txtDefCode.ReadOnly = true;
            //this._defcode = this.txtDefCode.Text;
        }

        private void showData(string defcode)
        {
            DataDBDataContext dbcntxt = new DataDBDataContext
                    (ConfigurationManager.ConnectionStrings["TradeForm.Properties.Settings.dbConnectionString"].ConnectionString);


            BillExchange billex = new BillExchange();
            ProFormaInvoice pinv = new ProFormaInvoice();
            ProFormaInvoiceGoods pinvGoods = new ProFormaInvoiceGoods();
            Invoice inv = new Invoice();
            Contract cont = new Contract();
            CustomsDeclaration cust = new CustomsDeclaration();
            ConsignBill consb = new ConsignBill();
            PackList pack = new PackList();
            GoodsSummery goodsSum = new GoodsSummery();

            if (this.IsNew)
            {
                this.txtDefCode.Text = defcode + "-1";
            }
            else
            {
                this.txtDefCode.Text = defcode;
            }

            #region //BillExchange
            var billexs = from bill in dbcntxt.BillExchange
                          where bill.DefCode == defcode
                          select bill;
            if (billexs.Count() > 0)
            {
                billex = billexs.First();
                this.txtBiExAddress.Text = billex.Address;
                this.txtBiExNo.Text = billex.BiExNo;
                this.txtBiExCurrency.Text = billex.Currency;
                this.txtBiExAmount.Text = billex.Amount.HasValue ? billex.Amount.Value.ToString("F2") : "0.00";
                this.txtBiExInterest.Text = billex.Interest;
                this.txtBiExLCBank.Text = billex.LCBank;
                this.dtpBiExLCDate.Value = billex.LCDate.HasValue ? billex.LCDate.Value : DateTime.MinValue;
                this.txtBiExLCno.Text = billex.LCno;
                this.txtBiExDays.Text = billex.LimitDays;
                this.txtBiExPayee.Text = billex.Payee;
                this.txtBiExPayer.Text = billex.Payer;
                this.txtBiExAmountSay.Text = billex.AmountSay;
            }
            #endregion

            #region //ProFormaInvoice
            var pinvs = from bill in dbcntxt.ProFormaInvoice
                        where bill.DefCode == defcode
                        select bill;
            if (pinvs.Count() > 0)
            {
                pinv = pinvs.First();
                this.txtProFormaConsignee.Text = pinv.Consignee;
                this.cmbProFormaDestPort.Text = pinv.DestPort;
                this.cmbProFormaFromPort.Text = pinv.FromPort;
                this.txtProFormaPayeeInfo.Text = pinv.GatherInfo;
                this.dtpProFormaDate.Value = pinv.InvoiceDate.HasValue ? pinv.InvoiceDate.Value : DateTime.MinValue;
                this.txtProFormaInvoiceNo.Text = pinv.InvoiceNo;
                this.txtProFormaRemark.Text = pinv.Mark;
                this.cmbProFormaPriceTerms.Text = pinv.PriceTerms;
            }
            #endregion

            #region //ProFormaInvoiceGoods
            var pinvGoodss = from bill in dbcntxt.ProFormaInvoiceGoods
                             where bill.DefCode == defcode
                             select bill;
            this.dgvProforma.DataSource = pinvGoodss;
            #endregion

            #region //Invoice
            var invs = from bill in dbcntxt.Invoice
                       where bill.DefCode == defcode
                       select bill;
            if (invs.Count() > 0)
            {
                inv = invs.First();
                this.txtInvConsignee.Text = inv.Consignee;
                this.txtInvContractNo.Text = inv.ContractNo;
                this.cmbInvDestPort.Text = inv.DestPort;
                this.cmbInvFromPort.Text = inv.FromPort;
                this.dtpInvInvoiceDate.Value = inv.InvoiceDate.HasValue ? inv.InvoiceDate.Value : DateTime.MinValue;
                this.txtInvInvoiceNo.Text = inv.InvoiceNo;
                this.txtInvMarks.Text = inv.Mark;
                this.cmbInvPriceTerms.Text = inv.PriceTerms;
                this.txtInvRemark.Text = inv.Remark;
            }
            #endregion

            #region //Contract
            var conts = from bill in dbcntxt.Contract
                        where bill.DefCode == defcode
                        select bill;
            if (conts.Count() > 0)
            {
                cont = conts.First();
                this.txtContConsignee.Text = cont.Consignee;
                this.dtpContContractDate.Value = cont.ContractDate.HasValue ? cont.ContractDate.Value : DateTime.MinValue;
                this.txtContContractNo.Text = cont.ContractNo;
                this.cmbContDestPort.Text = cont.DestPort;
                this.cmbContFromPort.Text = cont.FromPort;
                this.cmbContPaymentMethod.Text = cont.PaymentMethod;
                this.cmbContPriceTerms.Text = cont.PriceTerms;
                this.txtContRemark.Text = cont.Remark;
                this.dtpContShipmentDate.Value = cont.ShipmentDate.HasValue ? cont.ShipmentDate.Value : DateTime.MinValue;
            }
            #endregion

            #region //CustomsDeclaration
            var custs = from bill in dbcntxt.CustomsDeclaration
                        where bill.DefCode == defcode
                        select bill;
            if (custs.Count() > 0)
            {
                cust = custs.First();
                this.txtCustApprovalNo.Text = cust.ApprovalNo;
                this.txtCustAttachFile.Text = cust.AttachFile;
                this.txtCustBillLadingNo.Text = cust.BillLadingNo;
                this.txtCustConsignor.Text = cust.Consignor;
                this.txtCustContainnerNO.Text = cust.ContainnerNO;
                this.txtCustContractNo.Text = cust.ContractNo;
                this.cmbCustConveyance.Text = cust.Conveyance;
                this.dtpCustCustomDate.Value = cust.CustomDate.HasValue ? cust.CustomDate.Value : DateTime.MinValue;
                this.cmbCustDestPort.Text = cust.DestPort;
                this.dtpCustExportDate.Value = cust.ExpDate.HasValue ? cust.ExpDate.Value : DateTime.MinValue;
                this.dtpCustFilDate.Value = cust.FillDate.HasValue ? cust.FillDate.Value : DateTime.MinValue;
                this.txtCustFreight.Text = cust.Freight;
                this.cmbCustFromPort.Text = cust.FromPort;
                this.txtCustGoodsFrom.Text = cust.GoodsFrom;
                this.txtCustInsurance.Text = cust.Insurance;
                this.txtCustManufacture.Text = cust.Manufacture;
                this.txtCustMark.Text = cust.Mark;
                this.txtCustOtherFees.Text = cust.MiscellaneousFees;
                this.txtCustOperateCom.Text = cust.OperateCompany;
                this.txtCustPackType.Text = cust.PackType;
                this.txtCustRecordNo.Text = cust.RecordNo;
                this.cmbCustRemittanceWay.Text = cust.Remittanceway;
                this.txtCustTax.Text = cust.Tax;
                this.txtCustTaxDutyFree.Text = cust.TaxDutyFree;
                this.txtCustGoodsNum.Text = cust.TotalCount.HasValue ? cust.TotalCount.Value.ToString("##0") : "0";
                this.txtCustGrossWeight.Text = cust.TotalGrossWeight.HasValue ? cust.TotalGrossWeight.Value.ToString("##0.00") : "0.00";
                this.txtCustNetWeight.Text = cust.TotalNetWeight.HasValue ? cust.TotalNetWeight.Value.ToString("##0.00") : "0.00";
                //this.txtCustTradeCountry.Text = cust.TradeCountry;
                this.txtCustTradeTerms.Text = cust.TradeKind;
                this.txtCustTransportMode.Text = cust.TransportMode;
                this.txtCustTurnoverWay.Text = cust.TurnoverWay;
                this.txtCustWarrantNo.Text = cust.WarrantNo;
                this.cmbCustTradeCountry.Text = cust.TradeCountry;
            }
            #endregion

            #region //ConsignBill
            var consbs = from bill in dbcntxt.ConsignBill
                         where bill.DefCode == defcode
                         select bill;
            if (consbs.Count() > 0)
            {
                consb = consbs.First();
                this.chkFreCanBatch.Checked = consb.CanBatch.HasValue ? consb.CanBatch.Value : false; ;
                this.chkFreCanTranshipment.Checked = consb.CanTranshipment.HasValue ? consb.CanTranshipment.Value : false; ; ;
                this.txtFreConsignee.Text = consb.Consignee;
                this.cmbFreDestPort.Text = consb.DestPort;
                // this.txtFreFreight.Text = consb.Freight;
                this.cmbFreFinalDestPort.Text = consb.FinalDestPort;
                this.txtFreMark.Text = consb.Mark;
                this.txtFreNotifyParty.Text = consb.NotifyParty;
                this.cmbFrePaymentTerms.Text = consb.PaymentMethod;
                this.dtpFreShipmentDate.Value = consb.ShipmentDate.HasValue ? consb.ShipmentDate.Value : DateTime.MinValue;
                this.txtFreShipper.Text = consb.Shipper;
                this.dtpFreValiDate.Value = consb.ValiDate.HasValue ? consb.ValiDate.Value : DateTime.MinValue;
                this.cmbFreLoadPort.Text = consb.FromPort;
                this.txtFreRemark.Text = consb.Remark;
            }
            #endregion

            #region //PackList
            var packs = from bill in dbcntxt.PackList
                        where bill.DefCode == defcode
                        select bill;
            if (packs.Count() > 0)
            {
                pack = packs.First();
                this.txtPackInvoiceNo.Text = pack.InvoiceNo;
                this.txtPackMark.Text = pack.Mark;
                this.txtPackTotalCount.Text = pack.TotalCount.HasValue ? pack.TotalCount.Value.ToString("##0") : "0";
                this.txtPackTotalCountUnit.Text = pack.TotalCountUnit;
                this.txtPackGoodsName.Text = pack.TotalGoodsName;
                this.txtPackRemark.Text = pack.Remark;
                this.txtPackContractNo.Text = pack.ContractNo;
                this.dtpPackDate.Value = pack.PackDate.HasValue ? pack.PackDate.Value : DateTime.Now;
            }
            #endregion

            #region //PackListGoods
            var packgoods = from bill in dbcntxt.PackListGoods
                            where bill.DefCode == defcode
                            select bill;
            this.gdvPacklist.DataSource = packgoods;
            #endregion

            #region //GoodsSummery
            var goodsSums = from bill in dbcntxt.GoodsSummery
                            where bill.DefCode == defcode
                            select bill;
            if (goodsSums.Count() > 0)
            {
                goodsSum = goodsSums.First();
                this.txtGreatAmount.Text = goodsSum.GreatAmount;
                this.txtPackType.Text = goodsSum.PackType;
                this.txtTotalCount.Text = goodsSum.TotalCount.HasValue ? goodsSum.TotalCount.Value.ToString("##0") : "0";
                this.txtTotalCName.Text = goodsSum.TotalCName;
                this.txtTotalCountUnit.Text = goodsSum.TotalCountUnit;
                this.txtTotalEName.Text = goodsSum.TotalEName;
                this.txtTotalGrossWeight.Text = goodsSum.TotalGrossWeight.HasValue ? goodsSum.TotalGrossWeight.Value.ToString("##0.00") : "0";
                this.txtTotalMeas.Text = goodsSum.TotalMeas.HasValue ? goodsSum.TotalMeas.Value.ToString("##0.000") : "0";
                this.txtTotalNetWeight.Text = goodsSum.TotalNetWeight.HasValue ? goodsSum.TotalNetWeight.Value.ToString("##0.00") : "0";
                this.txtTotalQty.Text = goodsSum.TotalQty.HasValue ? goodsSum.TotalQty.Value.ToString("##0") : "0";
                this.txtTotalQtyUnit.Text = goodsSum.TotalQtyUnit;

                this.txtTotalMeasUnit.Text = goodsSum.TotalMeasUnit;
                this.txtTotalNetWeightUnit.Text = goodsSum.TotalNetWeightUnit;
                this.txtTotalGrossWeightUnit.Text = goodsSum.TotalGrossWeightUnit;
            }
            #endregion

            #region //GoodsDetail
            var goods = from good in dbcntxt.GoodsDetail
                        where good.DefCode == defcode
                        select good;
            this.dataGridView1.DataSource = goods;
            #endregion

            if (this.IsNew)
            {
                this.txtDefCode.ReadOnly = false;
            }
            else
            {
                this.txtDefCode.ReadOnly = true;
            }

        }

        private void FrmTradeForm_Load(object sender, EventArgs e)
        {
            this.dataGridView1.AutoGenerateColumns = false;
            this.gdvPacklist.AutoGenerateColumns = false;
            this.dgvProforma.AutoGenerateColumns = false;
            if (!string.IsNullOrEmpty(this._defcode))
            {
                showData(this._defcode);
            }
            if (IsNew)
            {
                this.Text = "新建单证";
            }
            else
            {
                this.Text = "编辑单证";
            }
            this.ColNetWeightUnit.DefaultCellStyle.NullValue = "KGS";
            this.ColMeasuresUnit.DefaultCellStyle.NullValue = "M3";
            this.ColGrossWeightUnit.DefaultCellStyle.NullValue = "KGS";
        }

        //private void cmbDestPort_KeyPress(object sender, KeyPressEventArgs e)
        //{
        //    if (e.KeyChar == (char)Keys.Enter)
        //    {
        //        ComboBox cmb = (ComboBox)sender;
        //        if (!string.IsNullOrEmpty(cmb.Text))
        //        {
        //            DataDBDataContext dbcntxt = new DataDBDataContext
        //           (ConfigurationManager.ConnectionStrings["TradeForm.Properties.Settings.dbConnectionString"].ConnectionString);
        //            var ports = from port in dbcntxt.Port
        //                        where port.PortCode.Contains(cmb.Text)
        //                        select port;
        //            DataTable DataTable1 = new DataTable();

        //            DataTable1.Columns.Add("PortCode", typeof(string));
        //            DataTable1.Columns.Add("CName", typeof(string));
        //            cmb.BeginUpdate();
        //            foreach (var item in ports)
        //            {
        //                Port port = (Port)item;
        //                DataTable1.Rows.Add(port.PortCode, port.CName);
        //            }
        //            cmb.DisplayMember = "CName";
        //            cmb.ValueMember = "PortCode";
        //            cmb.DataSource = DataTable1;
        //            cmb.EndUpdate();
        //            //cmb.SelectedIndex = 1;
        //            //cmb.DroppedDown = true;
        //            // cmb.DropDownStyle = ComboBoxStyle.DropDownList;
        //        }
        //        else
        //        {
        //            this.SelectNextControl(this.ActiveControl, true, true, false, true);
        //        }
        //        //e.Handled = true;
        //    }
        //}



        //private void btnSelectDestPort_Click(object sender, EventArgs e)
        //{
        //    FrmCode frm = new FrmCode();
        //    if (frm.ShowDialog() == DialogResult.OK)
        //    {
        //         this.cmb.Text = frm.ReturnName;
        //    }
        //}

        //private void btnSelectFromPort_Click(object sender, EventArgs e)
        //{
        //    FrmCode frm = new FrmCode();
        //    if (frm.ShowDialog() == DialogResult.OK)
        //    {
        //        // this.txtFromPort.Text = frm.ReturnName;
        //    }
        //}

        //private void btnSelectTransPort_Click(object sender, EventArgs e)
        //{
        //    FrmCode frm = new FrmCode();
        //    if (frm.ShowDialog() == DialogResult.OK)
        //    {
        //        // this.txtTranshipmentPort.Text = frm.ReturnName;
        //    }
        //}

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (this.IsNew)
            {
                MessageBox.Show("先保存数据。", "注意", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                FrmPrint fr = new FrmPrint(this.txtDefCode.Text, this.tabControl1.SelectedTab.Text);
                //fr.MdiParent = this.MdiParent;
                fr.ShowDialog();
            }

        }

        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {

            DataGridView gdv = (DataGridView)sender;
            gdv.Rows[e.RowIndex].ErrorText = "";
            if (e.FormattedValue != null && !string.IsNullOrEmpty(e.FormattedValue.ToString()) &&
                (gdv.Columns[e.ColumnIndex].Name == "ColQty" || gdv.Columns[e.ColumnIndex].Name == "ColUnitPrice" ||
                gdv.Columns[e.ColumnIndex].Name == "ColAmount" || gdv.Columns[e.ColumnIndex].Name == "ColMeasures" ||
                gdv.Columns[e.ColumnIndex].Name == "ColGrossWeight" || gdv.Columns[e.ColumnIndex].Name == "ColNetWeight"))
            {
                if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
                try
                {
                    decimal cellValue = Convert.ToDecimal(e.FormattedValue);
                }
                catch
                {
                    e.Cancel = true;
                    gdv.Rows[e.RowIndex].ErrorText = "只能输入数字";

                }
            }
        }

        private void btnProFormaFromPort_Click(object sender, EventArgs e)
        {
            FrmCode frm = new FrmCode();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.cmbProFormaFromPort.Text = frm.ReturnName;
            }
        }

        private void btnProFormaDestPort_Click(object sender, EventArgs e)
        {
            FrmCode frm = new FrmCode();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.cmbProFormaDestPort.Text = frm.ReturnName;
            }
        }

        private void btnContFromPort_Click(object sender, EventArgs e)
        {
            FrmCode frm = new FrmCode();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.cmbContFromPort.Text = frm.ReturnName;
            }
        }

        private void btnContDestPort_Click(object sender, EventArgs e)
        {
            FrmCode frm = new FrmCode();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.cmbContDestPort.Text = frm.ReturnName;
            }
        }

        private void btnInvFromPort_Click(object sender, EventArgs e)
        {
            FrmCode frm = new FrmCode();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.cmbInvFromPort.Text = frm.ReturnName;
            }
        }

        private void btnInvDestPort_Click(object sender, EventArgs e)
        {
            FrmCode frm = new FrmCode();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.cmbInvDestPort.Text = frm.ReturnName;
            }
        }

        private void btnCustFromPort_Click(object sender, EventArgs e)
        {
            FrmCode frm = new FrmCode();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.cmbCustFromPort.Text = frm.ReturnName;
            }
        }

        private void btnCustDestPort_Click(object sender, EventArgs e)
        {
            FrmCode frm = new FrmCode();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.cmbCustDestPort.Text = frm.ReturnName;
            }
        }

        private void btnFreDestPort_Click(object sender, EventArgs e)
        {
            FrmCode frm = new FrmCode();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.cmbFreDestPort.Text = frm.ReturnName;
            }
        }

        private void btnFreLoadPort_Click(object sender, EventArgs e)
        {
            FrmCode frm = new FrmCode();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.cmbFreLoadPort.Text = frm.ReturnName;
            }
        }

        private void btnFreFinalDestPort_Click(object sender, EventArgs e)
        {
            FrmCode frm = new FrmCode();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.cmbFreFinalDestPort.Text = frm.ReturnName;
            }
        }

        private void btnCustCountry_Click(object sender, EventArgs e)
        {
            FrmCode frm = new FrmCode("country");
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.cmbCustTradeCountry.Text = frm.ReturnName;
            }
        }

        /// <summary>
        /// 装箱单复制相同的内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabPackList_Enter(object sender, EventArgs e)
        {
            // if (string.IsNullOrEmpty(txtPackMark.Text))
            {
                this.txtPackMark.Text = this.txtInvMarks.Text;
            }

            // if (string.IsNullOrEmpty(txtPackInvoiceNo.Text))
            {
                this.txtPackInvoiceNo.Text = this.txtInvInvoiceNo.Text;
            }
            this.txtPackContractNo.Text = this.txtContContractNo.Text;
        }

        /// <summary>
        /// 托运单复制相同的内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabPageTransport_Enter(object sender, EventArgs e)
        {
            // if (string.IsNullOrEmpty(txtFreMark.Text))
            {
                this.txtFreMark.Text = this.txtInvMarks.Text;
            }
            // if (string.IsNullOrEmpty(txtFreDestPort.Text))
            {
                this.cmbFreDestPort.Text = this.cmbContDestPort.Text;
            }
            // if (string.IsNullOrEmpty(txtFreLoadPort.Text))
            {
                this.cmbFreLoadPort.Text = this.cmbContFromPort.Text;
            }

            this.cmbFrePaymentTerms.Text = this.cmbContPaymentMethod.Text;
            this.cmbFreFinalDestPort.Text = this.cmbContDestPort.Text;
        }

        private void txtDefCode_Leave(object sender, EventArgs e)
        {
            // if (!string.IsNullOrEmpty(this.txtDefCode.Text) && string.IsNullOrEmpty(this.txtContContractNo.Text))
            {
                this.txtContContractNo.Text = this.txtDefCode.Text;
            }
            //if (!string.IsNullOrEmpty(this.txtDefCode.Text) && string.IsNullOrEmpty(this.txtInvContractNo.Text))
            {
                this.txtInvContractNo.Text = this.txtDefCode.Text;
            }
        }

        /// <summary>
        /// 报关单复制相同的内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabPageCustom_Enter(object sender, EventArgs e)
        {
            //if (string.IsNullOrEmpty(txtCustDestPort.Text))
            {
                this.cmbCustDestPort.Text = this.cmbContDestPort.Text;
            }
            // if (string.IsNullOrEmpty(txtCustFromPort.Text))
            {
                this.cmbCustFromPort.Text = this.cmbContFromPort.Text;
            }
            //  if (string.IsNullOrEmpty(txtCustContractNo.Text))
            {
                this.txtCustContractNo.Text = this.txtInvInvoiceNo.Text;
            }

        }

        /// <summary>
        /// 汇票复制相同内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabPageBillChange_Enter(object sender, EventArgs e)
        {
            decimal amount = 0.0m;
            // if (string.IsNullOrEmpty(txtBiExNo.Text))
            {
                this.txtBiExNo.Text = this.txtInvInvoiceNo.Text;
            }
            //if (string.IsNullOrEmpty(this.txtBiExAmount.Text) && this.dataGridView1.Rows.Count > 0)
            if (this.dataGridView1.Rows.Count > 0)
            {
                amount = GetTotalAmount(this.dataGridView1, "ColAmount");
                this.txtBiExAmount.Text = amount == 0.0m ? "" : amount.ToString("##0.00");
            }

            // if (string.IsNullOrEmpty(this.txtBiExGreateAmount.Text) && !string.IsNullOrEmpty(this.txtBiExAmount.Text))
            if (!string.IsNullOrEmpty(this.txtBiExAmount.Text))
            {
                double totalAmount = Convert.ToDouble(this.txtBiExAmount.Text);
                if (totalAmount > 0.0D)
                {
                    this.txtBiExGreateAmount.Text = Number2English.NumberToString(totalAmount);
                }
            }
        }

        /// <summary>
        /// 根据列名获取当列的合计
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private decimal GetTotalAmount(DataGridView grid, string colName)
        {
            decimal totalAmount = 0.0m;
            foreach (DataGridViewRow item in grid.Rows)
            {
                if (!item.IsNewRow)
                {
                    totalAmount += (item.Cells[colName].Value == null || string.IsNullOrEmpty(item.Cells[colName].Value.ToString()) ?
                        0.0m : Convert.ToDecimal(item.Cells[colName].Value));
                }
            }
            return totalAmount;
        }

        private void txtGreatAmount_Enter(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtGreatAmount.Text))
            {
                GentGreatAmount();
            }
        }

        private void GentGreatAmount()
        {
            decimal totalAmount = 0.0m;
            if (this.dataGridView1.Rows.Count > 0)
            {
                totalAmount = GetTotalAmount(this.dataGridView1, "ColAmount");
                if (totalAmount > 0.0m)
                {
                    this.txtGreatAmount.Text = Number2English.NumberToString(Convert.ToDouble(totalAmount));
                }
            }
        }

        private void btnGentGreatAmount_Click(object sender, EventArgs e)
        {
            GentGreatAmount();
        }

        //private void FrmTradeForm_KeyPress(object sender, KeyPressEventArgs e)
        //{
        //    if (e.KeyChar == (char)Keys.Enter)
        //    {
        //        e.KeyChar = (char)Keys.Tab;
        //        // e.Handled = false;
        //        //this.SelectNextControl(this.ActiveControl, true, true, false, true);
        //    }
        //}

        /// <summary>
        /// 复制发票相同内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabPageInvoice_Enter(object sender, EventArgs e)
        {
            this.cmbInvFromPort.Text = this.cmbContFromPort.Text;
            this.cmbInvDestPort.Text = this.cmbContDestPort.Text;
            this.cmbInvPriceTerms.Text = this.cmbContPriceTerms.Text;
        }

        private void tabControl1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                Control ctrl = null;
                ctrl = grpCustoms.Controls[0];
                foreach (Control item in grpCustoms.Controls)
                {
                    if (item.Focused == true)
                    {
                        ctrl = item;
                        break;
                    }
                }
                if (ctrl.GetType() != System.Type.GetType("System.Windows.Forms.Button"))
                {
                    this.grpCustoms.SelectNextControl(ctrl, true, true, false, true);
                }

            }
        }

        private void cmbContFromPort_KeyPress(object sender, KeyPressEventArgs e)
        {

            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cmb = (ComboBox)sender;
                if (!string.IsNullOrEmpty(cmb.Text) && cmb.DroppedDown == false)
                {
                    DataDBDataContext dbcntxt = new DataDBDataContext
                   (ConfigurationManager.ConnectionStrings["TradeForm.Properties.Settings.dbConnectionString"].ConnectionString);
                    var ports = from port in dbcntxt.Port
                                where port.PortCode.Contains(cmb.Text)
                                select port;
                    DataTable DataTable1 = new DataTable();

                    DataTable1.Columns.Add("PortCode", typeof(string));
                    DataTable1.Columns.Add("EName", typeof(string));
                    cmb.BeginUpdate();
                    foreach (var item in ports)
                    {
                        Port port = (Port)item;
                        DataTable1.Rows.Add(port.PortCode, port.EName.ToUpper());
                    }
                    cmb.DisplayMember = "EName";
                    cmb.ValueMember = "PortCode";
                    cmb.DataSource = DataTable1;
                    cmb.EndUpdate();
                    cmb.DroppedDown = true;
                    e.Handled = true;
                }
                else
                {
                    cmb.DroppedDown = false;

                    Control ctrl = null;
                    ctrl = groupBox1.Controls[0];
                    foreach (Control item in groupBox1.Controls)
                    {
                        if (item.Focused == true)
                        {
                            ctrl = item;
                            break;
                        }
                    }
                    if (ctrl.GetType() != System.Type.GetType("System.Windows.Forms.Button"))
                    {
                        this.groupBox1.SelectNextControl(ctrl, true, true, false, true);
                    }
                }
                //e.Handled = true;
            }
        }

        private void cmbInvFromPort_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cmb = (ComboBox)sender;
                GroupBox groupbox = (GroupBox)cmb.Parent;
                if (!string.IsNullOrEmpty(cmb.Text) && cmb.DroppedDown == false)
                {
                    DataDBDataContext dbcntxt = new DataDBDataContext
                   (ConfigurationManager.ConnectionStrings["TradeForm.Properties.Settings.dbConnectionString"].ConnectionString);
                    var ports = from port in dbcntxt.Port
                                where port.PortCode.Contains(cmb.Text)
                                select port;
                    DataTable DataTable1 = new DataTable();

                    DataTable1.Columns.Add("PortCode", typeof(string));
                    DataTable1.Columns.Add("EName", typeof(string));
                    cmb.BeginUpdate();
                    foreach (var item in ports)
                    {
                        Port port = (Port)item;
                        DataTable1.Rows.Add(port.PortCode, port.EName.ToUpper());
                    }
                    cmb.DisplayMember = "EName";
                    cmb.ValueMember = "PortCode";
                    cmb.DataSource = DataTable1;
                    cmb.EndUpdate();
                    cmb.DroppedDown = true;
                    e.Handled = true;
                }
                else
                {
                    cmb.DroppedDown = false;

                    Control ctrl = null;
                    ctrl = groupbox.Controls[0];
                    foreach (Control item in groupbox.Controls)
                    {
                        if (item.Focused == true)
                        {
                            ctrl = item;
                            break;
                        }
                    }
                    if (ctrl.GetType() != System.Type.GetType("System.Windows.Forms.Button"))
                    {
                        groupbox.SelectNextControl(ctrl, true, true, false, true);
                    }
                }
            }
        }

        private void cmbCustTradeCountry_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cmb = (ComboBox)sender;
                GroupBox groupbox = (GroupBox)cmb.Parent;
                if (!string.IsNullOrEmpty(cmb.Text) && cmb.DroppedDown == false)
                {
                    DataDBDataContext dbcntxt = new DataDBDataContext
                   (ConfigurationManager.ConnectionStrings["TradeForm.Properties.Settings.dbConnectionString"].ConnectionString);
                    var countrys = from country in dbcntxt.Country
                                   where country.CountryCode.Contains(cmb.Text)
                                   select country;
                    DataTable DataTable1 = new DataTable();

                    DataTable1.Columns.Add("CountryCode", typeof(string));
                    DataTable1.Columns.Add("EName", typeof(string));
                    cmb.BeginUpdate();
                    foreach (var item in countrys)
                    {
                        Country country = (Country)item;
                        DataTable1.Rows.Add(country.CountryCode, country.EName.ToUpper());
                    }
                    cmb.DisplayMember = "EName";
                    cmb.ValueMember = "CountryCode";
                    cmb.DataSource = DataTable1;
                    cmb.EndUpdate();
                    cmb.DroppedDown = true;
                    e.Handled = true;
                }
                else
                {
                    cmb.DroppedDown = false;
                    Control ctrl = null;
                    ctrl = groupbox.Controls[0];
                    foreach (Control item in groupbox.Controls)
                    {
                        if (item.Focused == true)
                        {
                            ctrl = item;
                            break;
                        }
                    }
                    if (ctrl.GetType() != System.Type.GetType("System.Windows.Forms.Button"))
                    {
                        groupbox.SelectNextControl(ctrl, true, true, false, true);
                    }
                }
            }
        }

        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].Name == "ColAmount")
            {
                if (!string.IsNullOrEmpty(dataGridView1.Rows[e.RowIndex].Cells["ColUnitPrice"].Value.ToString())
                    && !string.IsNullOrEmpty(dataGridView1.Rows[e.RowIndex].Cells["ColQty"].Value.ToString()))
                {
                    try
                    {
                        decimal qty = Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells["ColQty"].Value);
                        decimal price = Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells["ColUnitPrice"].Value);
                        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = qty * price;
                    }
                    catch
                    {

                    }
                }
            }
        }

        private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].Name == "ColQty"
              || dataGridView1.Columns[e.ColumnIndex].Name == "ColUnitPrice")
            {
                if (dataGridView1.Rows[e.RowIndex].Cells["ColUnitPrice"].Value != null
                    && !string.IsNullOrEmpty(dataGridView1.Rows[e.RowIndex].Cells["ColUnitPrice"].Value.ToString())
                    && dataGridView1.Rows[e.RowIndex].Cells["ColQty"].Value != null
                    && !string.IsNullOrEmpty(dataGridView1.Rows[e.RowIndex].Cells["ColQty"].Value.ToString()))
                {
                    try
                    {
                        decimal qty = Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells["ColQty"].Value);
                        decimal price = Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells["ColUnitPrice"].Value);
                        dataGridView1.Rows[e.RowIndex].Cells["ColAmount"].Value = qty * price;
                    }
                    catch
                    {

                    }
                }
            }
        }

        //private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
        //{
        //    if (dataGridView1.Columns[e.ColumnIndex].Name == "ColQty"
        //        || dataGridView1.Columns[e.ColumnIndex].Name == "ColUnitPrice")
        //    {
        //        if (!string.IsNullOrEmpty(dataGridView1.Rows[e.RowIndex].Cells["ColUnitPrice"].Value.ToString())
        //             && !string.IsNullOrEmpty(dataGridView1.Rows[e.RowIndex].Cells["ColQty"].Value.ToString()))
        //        {
        //            try
        //            {
        //                decimal qty = Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells["ColQty"].Value);
        //                decimal price = Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells["ColUnitPrice"].Value);
        //                dataGridView1.Rows[e.RowIndex].Cells["ColAmount"].Value = qty * price;
        //            }
        //            catch
        //            {

        //            }
        //        }
        //    }
        //}


        //private void Number_Validated(object sender, EventArgs e)
        //{
        //    if (sender.GetType() == typeof(System.Windows.Forms.TextBox))
        //    {
        //        TextBox txt = (TextBox)sender;
        //        try
        //        {
        //            if (!string.IsNullOrEmpty(txt.Text.Trim()))
        //            {
        //                Convert.ToDecimal(txt.Text.Trim());
        //            }
        //            errorProvider1.SetError(txt, "");
        //        }
        //        catch
        //        {
        //            errorProvider1.SetError(txt, "必须数字.");
        //        }

        //    }
        //}








    }
}
